package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.BehaviorMapper;
import com.heima.behavior.service.BehaviorService;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.LikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.article.ApArticle;
import com.heima.model.common.pojos.behavior.ReadBehavior;
import com.heima.model.common.pojos.behavior.UnLikesBehavior;
import com.heima.utils.thread.ApThreadLocalUtil;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author Geralt
 * @Date 2024-08-01 10:02
 */
@Service
public class BehaviorServiceImpl extends ServiceImpl<BehaviorMapper, ApArticle> implements BehaviorService {
    @Autowired
    private CacheService cacheService;

    /**
     * 文章点赞
     *
     * @param likesBehaviorDto
     * @return
     */
    @Override
    public ResponseResult likesBehavior(LikesBehaviorDto likesBehaviorDto) {
        //0.参数校验
        if (likesBehaviorDto == null && likesBehaviorDto.getArticleId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer userId = ApThreadLocalUtil.get();
        //1.1 判断点点赞的内容：0：文章  1：动态   2：评论
        //1.2修改文章点赞数量  likes 0 点赞 点赞记录+1   1 取消点赞 点赞记录-1
        //保存数据到数据库
        ApArticle article = getOne(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId, likesBehaviorDto.getArticleId()));
        Integer likes = article.getLikes();
        if (likes == null) {
            likes = 0;
        }
        if (likesBehaviorDto.getOperation() == 0) {
            //点赞操作
            article.setLikes(likes + 1);
            update(Wrappers.<ApArticle>lambdaUpdate().set(ApArticle::getLikes, article.getLikes())
                    .eq(ApArticle::getId, article.getId()));
        } else {
            //取消点赞操作
            article.setLikes(likes - 1);
            update(Wrappers.<ApArticle>lambdaUpdate().set(ApArticle::getLikes, article.getLikes())
                    .eq(ApArticle::getId, article.getId()));
        }
        //保存数据到Redis  key:设置为当前用户id  logs_userId
        Map<String, Object> map = new HashMap<>();
        map.put("data", likesBehaviorDto);
        cacheService.hPut("likes_logs:" + userId.toString(), article.getId().toString(), JSON.toJSONString(map));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 阅读文章
     *
     * @param behaviorDto
     * @return
     */
    @Override
    public ResponseResult readBehavior(LikesBehaviorDto behaviorDto) {
        //0.参数校验
        if (behaviorDto == null || behaviorDto.getArticleId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle article = getOne(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId, behaviorDto.getArticleId()));
        Integer views = article.getViews();
        if (views == null) {
            views = 0;
        }
        ReadBehavior behaviorRead = new ReadBehavior();
        BeanUtils.copyProperties(behaviorDto, behaviorRead);
        Integer userId = ApThreadLocalUtil.get();
        //1.从Redis中查询该用户阅读了该文章多少次
        Object value = cacheService.hGet("read_logs:" + userId.toString(), behaviorDto.getArticleId().toString());
        if (value != null) {
            Map parseObject = JSON.parseObject(value.toString(), Map.class);
            //1.1 数据存在，count + 1
            ReadBehavior read = JSONArray.parseObject(parseObject.get("data").toString(), ReadBehavior.class);
            behaviorRead.setCount(read.getCount() + 1);
            //存入到Redis中
        }
        //1.2 不存在直接保存到Redis中
        Map<String, Object> map = new HashMap<>();
        map.put("data", behaviorRead);
        cacheService.hPut("read_logs:" + userId, behaviorRead.getArticleId().toString(), JSON.toJSONString(map));
        //2.将数据库中article中的 views + 1。
        article.setViews(views + 1);
        update(Wrappers.<ApArticle>lambdaUpdate().set(ApArticle::getViews, article.getViews())
                .eq(ApArticle::getId, behaviorDto.getArticleId()));
        //返回
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 不喜欢操作
     *
     * @param behaviorDto
     * @return
     */
    @Override
    public ResponseResult unLikesBehavior(LikesBehaviorDto behaviorDto) {
        //参数校验
        if (behaviorDto == null || behaviorDto.getArticleId() == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        //1.根据文章id获取文章的标签，整合标签存入到Redis中
        ApArticle article = getOne(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId, behaviorDto.getArticleId()));
        List<String> list = new ArrayList<>();
        if (article != null) {
            //查询文章标签
            String labels = article.getLabels();
            String[] split = labels.split(",");
            list.addAll(Arrays.asList(split));
        }
        UnLikesBehavior unLikesBehavior = new UnLikesBehavior();
        unLikesBehavior.setArticleId(behaviorDto.getArticleId());
        unLikesBehavior.setLabels(list);
        //tyre: 0代表添加不喜欢  1：代表取消不喜欢
        if (behaviorDto.getType() == 1) {
            unLikesBehavior.setIsUnLike(false);
        } else {
            unLikesBehavior.setIsUnLike(true);
        }
        //1.将操作记录保存到Redis中
        cacheService.hPut("un_likes_logs:" + ApThreadLocalUtil.get().toString(),
                behaviorDto.getArticleId().toString(), JSON.toJSONString(unLikesBehavior));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
